import { useState } from "react";
import {
  Form,
  Input,
  Button,
  Card,
  message,
  InputNumber,
  Upload,
  Switch,
  Space,
  Tooltip,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  UserAddOutlined,
  CopyrightOutlined,
  PlusOutlined,
  LoadingOutlined,
  SunOutlined,
  MoonOutlined,
  SendOutlined,
} from "@ant-design/icons";
import { useNavigate, Link } from "react-router-dom";
import { register, sendVerificationCode } from "../api/users";
import { uploadImage } from "../api/upload";
import { useTheme } from "../contexts/ThemeContext";

import { Typography } from "antd";
import ReactLogo from "../assets/react.svg";

const { Title, Paragraph } = Typography;

export default function Register() {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  const [uploading, setUploading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [codeSent, setCodeSent] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { isDarkMode, toggleDarkMode } = useTheme();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      // 检查验证码是否已发送
      if (!codeSent) {
        message.error("请先发送验证码");
        setLoading(false);
        return;
      }

      // 移除确认密码字段，只保留API需要的字段
      const { confirmPassword, ...registerData } = values;
      registerData.img =
        imageUrl ||
        "https://mix-web-demo.oss-cn-guangzhou.aliyuncs.com/pic/c87aef85d1ee4884b40097ec0339a613.jpg";

      console.log("发送注册请求:", registerData); // 调试日志

      const res = await register(registerData);
      console.log("注册响应:", res); // 调试日志

      if (res.code !== 1) {
        throw new Error(res.message || "注册失败");
      }

      // 保存用户信息到 localStorage，供登录页面使用
      localStorage.setItem(
        "registeredUserInfo",
        JSON.stringify({
          name: registerData.name,
          password: registerData.password,
        })
      );

      message.success("注册成功！请登录");
      navigate("/login");
    } catch (e) {
      console.error("注册失败:", e); // 调试日志

      // 更详细的错误信息
      let errorMessage = "注册失败";
      if (e.response) {
        // 服务器响应了错误状态码
        errorMessage =
          e.response.data?.message || `服务器错误: ${e.response.status}`;
      } else if (e.request) {
        // 请求已发出但没有收到响应
        errorMessage = "网络连接失败，请检查网络或后端服务是否正常运行";
      } else {
        // 其他错误
        errorMessage = e.message || "注册失败";
      }

      message.error(errorMessage);
    }
    setLoading(false);
  };

  // 发送验证码
  const handleSendCode = async () => {
    const email = form.getFieldValue("email");

    // 验证邮箱格式
    if (!email) {
      message.error("请先输入邮箱地址");
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      message.error("请输入有效的邮箱地址");
      return;
    }

    setSendingCode(true);
    try {
      const res = await sendVerificationCode(email);
      console.log("验证码发送响应:", res);

      if (res.code === 1) {
        message.success("验证码已发送，请查看邮箱");
        setCodeSent(true);
        // 开启60秒倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        throw new Error(res.message || "发送验证码失败");
      }
    } catch (error) {
      console.error("发送验证码失败:", error);
      message.error(error.message || "发送验证码失败，请重试");
    } finally {
      setSendingCode(false);
    }
  };

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("只能上传 JPG/PNG 格式的图片!");
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("图片大小不能超过 2MB!");
      return false;
    }
    return true;
  };

  const handleUpload = async ({ file, onSuccess, onError }) => {
    setUploading(true);
    try {
      // 使用真实的上传接口
      const res = await uploadImage(file);
      console.log("上传响应:", res); // 调试日志

      if (res.code === 1 && res.data && res.data.oss_url) {
        setImageUrl(res.data.oss_url);
        onSuccess();
        message.success("头像上传成功");
      } else {
        throw new Error(res.message || res.msg || "上传失败");
      }
    } catch (error) {
      console.error("头像上传失败:", error);
      onError(error);
      message.error(error.message || "头像上传失败");
    }
    setUploading(false);
  };

  const uploadButton = (
    <div>
      {uploading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传头像</div>
    </div>
  );

  return (
    <div
      style={{
        minHeight: "100vh",
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        background: isDarkMode
          ? "linear-gradient(135deg, #1f1f1f 0%, #2a2a2a 100%)"
          : "linear-gradient(135deg, #f0f5ff 0%, #e6f7ff 100%)",
        position: "relative",
        overflow: "hidden",
        transition: "background 0.3s ease",
      }}>
      {/* 主题切换按钮 */}
      <div
        style={{
          position: "absolute",
          top: 20,
          right: 20,
          zIndex: 10,
        }}>
        <Tooltip title={isDarkMode ? "切换到浅色模式" : "切换到深色模式"}>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: "8px",
              padding: "8px 12px",
              borderRadius: "6px",
              backgroundColor: isDarkMode ? "#2a2a2a" : "#f5f5f5",
              border: `1px solid ${isDarkMode ? "#434343" : "#d9d9d9"}`,
              cursor: "pointer",
              transition: "all 0.3s ease",
            }}
            onClick={toggleDarkMode}>
            <Space size="small">
              {isDarkMode ? (
                <MoonOutlined style={{ color: "#1890ff" }} />
              ) : (
                <SunOutlined style={{ color: "#faad14" }} />
              )}
              <span
                style={{
                  fontSize: "12px",
                  color: isDarkMode ? "#fff" : "#666",
                }}>
                {isDarkMode ? "深色" : "浅色"}
              </span>
            </Space>
            <Switch
              size="small"
              checked={isDarkMode}
              onChange={toggleDarkMode}
              checkedChildren={<MoonOutlined />}
              unCheckedChildren={<SunOutlined />}
            />
          </div>
        </Tooltip>
      </div>

      {/* 左侧渐变圆形装饰 */}
      <div
        style={{
          position: "absolute",
          left: -120,
          top: "30%",
          width: 220,
          height: 220,
          background: isDarkMode
            ? "radial-gradient(circle at 60% 40%, #3a3a3a 0%, #2a2a2a 80%)"
            : "radial-gradient(circle at 60% 40%, #91d5ff 0%, #e6f7ff 80%)",
          opacity: 0.35,
          borderRadius: "50%",
          zIndex: 0,
          filter: "blur(2px)",
          transition: "background 0.3s ease",
        }}
      />
      {/* 右侧渐变圆形装饰 */}
      <div
        style={{
          position: "absolute",
          right: -100,
          bottom: "18%",
          width: 180,
          height: 180,
          background: isDarkMode
            ? "radial-gradient(circle at 40% 60%, #404040 0%, #2a2a2a 80%)"
            : "radial-gradient(circle at 40% 60%, #bae7ff 0%, #e6f7ff 80%)",
          opacity: 0.32,
          borderRadius: "50%",
          zIndex: 0,
          filter: "blur(2px)",
          transition: "background 0.3s ease",
        }}
      />
      {/* 顶部小圆点装饰 */}
      <div
        style={{
          position: "absolute",
          top: 32,
          left: "50%",
          transform: "translateX(-50%)",
          width: 16,
          height: 16,
          background: isDarkMode ? "#1890ff44" : "#1890ff22",
          borderRadius: "50%",
          boxShadow: isDarkMode ? "0 0 8px #1890ff77" : "0 0 8px #1890ff55",
          zIndex: 1,
          transition: "all 0.3s ease",
        }}
      />
      <Card
        style={{
          width: 420,
          borderRadius: 18,
          boxShadow: isDarkMode
            ? "0 4px 32px rgba(0,0,0,0.3), 0 1.5px 8px rgba(0,0,0,0.2)"
            : "0 4px 32px #e6f7ff, 0 1.5px 8px #b3d8ff33",
          padding: 0,
          position: "relative",
          overflow: "hidden",
          transition: "box-shadow 0.3s cubic-bezier(.4,2,.6,1)",
          backgroundColor: isDarkMode ? "#2a2a2a" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        }}
        variant="outlined"
        styles={{
          body: { padding: "32px 32px 24px 32px" },
        }}
        hoverable>
        {/* 卡片底部渐变装饰 */}
        <div
          style={{
            position: "absolute",
            left: 0,
            bottom: 0,
            width: "100%",
            height: 60,
            background: isDarkMode
              ? "linear-gradient(90deg, #1f1f1f 0%, #3a3a3a 100%)"
              : "linear-gradient(90deg, #e6f7ff 0%, #bae7ff 100%)",
            opacity: 0.18,
            zIndex: 0,
            transition: "background 0.3s ease",
          }}
        />
        <div
          style={{
            textAlign: "center",
            marginBottom: 24,
            marginTop: 8,
            position: "relative",
            zIndex: 2,
          }}>
          <img
            src={ReactLogo}
            alt="logo"
            style={{
              width: 56,
              marginBottom: 8,
              filter: "drop-shadow(0 2px 8px #bae7ff)",
            }}
          />
          <Title
            level={3}
            style={{
              color: "#1890ff",
              marginBottom: 0,
              letterSpacing: 2,
            }}>
            欢迎注册
          </Title>
          <Paragraph
            style={{
              color: isDarkMode ? "#bfbfbf" : "#888",
              marginBottom: 0,
              fontSize: 15,
              transition: "color 0.3s ease",
            }}>
            多语言微服务内容管理系统
          </Paragraph>
        </div>
        <Form
          form={form}
          onFinish={onFinish}
          layout="vertical"
          style={{ zIndex: 2, position: "relative" }}>
          <Form.Item
            name="name"
            rules={[
              { required: true, message: "请输入用户名" },
              { min: 2, message: "用户名至少2个字符" },
            ]}>
            <Input
              prefix={<UserOutlined style={{ color: "#1890ff" }} />}
              placeholder="用户名"
              size="large"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱地址" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
            extra={
              <div style={{ marginTop: 8 }}>
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={handleSendCode}
                  loading={sendingCode}
                  disabled={countdown > 0}
                  block
                  style={{
                    borderRadius: 6,
                    fontWeight: 500,
                  }}>
                  {countdown > 0 ? `重新发送 (${countdown}s)` : "发送验证码"}
                </Button>
              </div>
            }>
            <Input
              prefix={<MailOutlined style={{ color: "#1890ff" }} />}
              placeholder="邮箱地址"
              size="large"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>

          <Form.Item
            name="verificationCode"
            rules={[
              { required: true, message: "请输入邮箱验证码" },
              {
                pattern: /^\d{6}$/,
                message: "验证码必须是6位数字",
              },
            ]}>
            <Input
              prefix={<MailOutlined style={{ color: "#1890ff" }} />}
              placeholder="验证码（6位数字）"
              size="large"
              style={{ borderRadius: 8 }}
              maxLength={6}
            />
          </Form.Item>

          <Form.Item
            name="age"
            rules={[
              { required: true, message: "请输入年龄" },
              { type: "number", min: 1, max: 120, message: "请输入有效的年龄" },
            ]}>
            <InputNumber
              prefix={<UserAddOutlined style={{ color: "#1890ff" }} />}
              placeholder="年龄"
              size="large"
              style={{ width: "100%", borderRadius: 8 }}
              min={1}
              max={120}
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码至少6个字符" },
            ]}>
            <Input.Password
              prefix={<LockOutlined style={{ color: "#1890ff" }} />}
              placeholder="密码"
              size="large"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={["password"]}
            rules={[
              { required: true, message: "请确认密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("两次输入的密码不一致"));
                },
              }),
            ]}>
            <Input.Password
              prefix={<LockOutlined style={{ color: "#1890ff" }} />}
              placeholder="确认密码"
              size="large"
              style={{ borderRadius: 8 }}
            />
          </Form.Item>

          <Form.Item label="头像" style={{ marginBottom: 16 }}>
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={beforeUpload}
              customRequest={handleUpload}
              style={{ borderRadius: 8 }}>
              {imageUrl ? (
                <img
                  src={imageUrl}
                  alt="avatar"
                  style={{ width: "100%", borderRadius: 8 }}
                />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>

          <Form.Item style={{ marginBottom: 16 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
              style={{
                borderRadius: 8,
                background: "linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)",
                boxShadow: "0 2px 8px #bae7ff55",
                border: "none",
                fontWeight: 500,
                letterSpacing: 1,
              }}>
              注册
            </Button>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: "center" }}>
            <span style={{ color: isDarkMode ? "#bfbfbf" : "#888" }}>
              已有账号？
            </span>
            <Link
              to="/login"
              style={{
                color: "#1890ff",
                marginLeft: 8,
                textDecoration: "none",
              }}>
              立即登录
            </Link>
          </Form.Item>
        </Form>
      </Card>
      {/* 底部版权信息 */}
      <div
        style={{
          marginTop: 32,
          color: isDarkMode ? "#8c8c8c" : "#b3b3b3",
          fontSize: 13,
          letterSpacing: 1,
          display: "flex",
          alignItems: "center",
          gap: 4,
          userSelect: "none",
          transition: "color 0.3s ease",
        }}>
        <CopyrightOutlined /> 2025 多语言微服务内容管理系统
      </div>
    </div>
  );
}
